package cn.car.web.filter;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.car.web.util.GzipWrapper;

public class GzipFilter implements Filter {


	public void doFilter(ServletRequest servletrequest,
			ServletResponse servletresponse, FilterChain chain)
			throws IOException, ServletException {
		//先转成http类的
		HttpServletRequest request = (HttpServletRequest) servletrequest;
		HttpServletResponse response = (HttpServletResponse) servletresponse;
		//判断浏览器是否支持GZIP
		if(checkSupportGZip(request)){
			System.out.println("支持");
			//装饰加强response功能
			GzipWrapper wrapper = new GzipWrapper(response);
			//放行过一遍
			chain.doFilter(request, wrapper);
			//拿到响应返回的gzip压缩数据
			byte[] gzipDatas = getGzipData(wrapper.getResponseData());
			
			//告诉浏览器解压方式
			response.addHeader("Content-Encoding", "gzip");
			response.setContentLength(gzipDatas.length);
			//输出数据给浏览器
			ServletOutputStream output = response.getOutputStream();
			output.write(gzipDatas);
			output.flush();
		}else{
			System.out.println("不支持");
			//不支持的话,只能原样放回资源
			chain.doFilter(request, response);
		}
	}

	private byte[] getGzipData(byte[] data) {
		//设置缓存流大小为10kb
		ByteArrayOutputStream output = new ByteArrayOutputStream(10240);
		GZIPOutputStream gzipOutput = null;
		try{
			gzipOutput = new GZIPOutputStream(output);
			gzipOutput.write(data);
		}catch (Exception e) {
			//不做处理
		}finally{
			//关资源
			if(gzipOutput!=null){
				try{
					gzipOutput.close();
				}catch (Exception e) {}
			}
		}
		return output.toByteArray();
	}

	/**
	 * 检查浏览器是否支持Gzip压缩
	 * @param request
	 */
	private static boolean checkSupportGZip(HttpServletRequest request){
		//拿到头-访问编码
		String encoding = request.getHeader("Accept-Encoding");
		if(encoding.indexOf("gzip") != -1){
			return true;
		}
		return false;
	}
	
	public void destroy() {}
	public void init(FilterConfig filterconfig) throws ServletException {}

}
